package cn.stylefeng.guns.sys.modular.auth.util;

import cn.hutool.core.util.StrUtil;
import cn.stylefeng.guns.sys.modular.auth.constant.Constant;
import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author kongtao
 * @Date 2023/11/28 14:56
 */
public class CertAuthUtil {

    private static final Logger LOGGER = org.apache.logging.log4j.LogManager.getLogger(CertAuthUtil.class);

    /**
     * 执行命令
     *
     * @param cmd
     * @return
     */
    public static String executeCmd(String[] cmd) {
        Runtime run = Runtime.getRuntime();
        StringBuffer sb = new StringBuffer();
        Process process = null;
        InputStream in = null;
        BufferedReader bs = null;
        try {
            process = run.exec(cmd);
            in = process.getInputStream();
            bs = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String result = null;
            while ((result = bs.readLine()) != null) {
                sb.append(result);
            }

            process.waitFor();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        } finally {
            try {
                if (bs != null) {
                    bs.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
            }

            if (process != null) {
                process.destroy();
            }
        }

        return sb.toString();
    }


    /**
    *@description 生成客户端证书
    *@author kongtao
    *@date  2023/11/28 15:09
    **/
    public static String generateCert(String userName, String password) {
        if(StrUtil.isEmpty(userName) || StrUtil.isEmpty(password)) {
            LOGGER.error("generateCert error: userName or password is empty, userName:" + userName +", password:"+ password);
            return null;
        }

        List<String> list = new ArrayList<>();
        list.add(Constant.generateCertTool);
        list.add(userName);
        list.add(password);
        String certPath = executeCmd(list.toArray(new String[list.size()]));
        if(StrUtil.isNotEmpty(certPath) && certPath.contains("cert_path:")) {
            certPath = certPath.substring("cert_path:".length());
            LOGGER.info("generateCert success: userName:" + userName +", password:"+ password + ",certPath:" + certPath);
            return certPath;
        } else {
            LOGGER.error("generateCert fail: userName:" + userName +", password:"+ password + ",certPath:" + certPath);
        }

        return null;
    }

    public static boolean revokeCert(String certPath) {
        LOGGER.error("revoke cert path:" + certPath);
        if(StrUtil.isEmpty(certPath)) {
            LOGGER.error("revoke cert error: certPath is empty");
            return false;
        }

        certPath = certPath.replace(".p12", ".crt");
        List<String> list = new ArrayList<>();
        list.add(Constant.revokeCertTool);
        list.add(certPath);
        String result = executeCmd(list.toArray(new String[list.size()]));
        if(StrUtil.isEmpty(result) || certPath.contains("revoke cert fail:")) {
            LOGGER.info("revoke cert error, certPath:" + certPath);
            return false;
        }

        LOGGER.info("revoke cert success, certPath:" + certPath);
        return true;
    }

}
